﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.IO.Ports;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using Models;

namespace DAL
{
    //创建委托
    public delegate void GetMsgDelegate(byte[] buffer);

    public class JY61P
    {
        //创建委托对象
        public GetMsgDelegate myGetMsg;

        public SerialPort serialPort = new SerialPort();//创建一个端口


        #region 串口的打开与关闭


        /// <summary>
        /// 打开串口
        /// </summary>
        /// <param name="portName">串口名</param>
        /// <param name="baudRate">波特率，默认为9600</param>
        /// <param name="stopBits">停止位，默认为one</param>
        /// <param name="parity">校验位，默认为none</param>
        /// <param name="dataBits">数据位，默认为8</param>
        /// <returns>是否连接成功</returns>
        public bool Connection(Serial serial)
        {
            //若已打开则先关闭，便于新配置导入
            if (serialPort.IsOpen == true)
                serialPort.Close();

            //串口配置
            serialPort.PortName = serial.PortName;
            serialPort.BaudRate = serial.BaudRate;
            serialPort.StopBits = serial.StopBits;
            serialPort.Parity = serial.Check;
            serialPort.DataBits = serial.DataBits;

            //设置串口基本属性并接收事件
            serialPort.ReceivedBytesThreshold = 1;
            serialPort.DataReceived += SerialPort_DataReceived;


            try
            {
                this.serialPort.Open();
            }
            catch (Exception ex)
            {               
                //可以写入日志
                return false;
            }
            return true;
        }

        //关闭连接

        public bool DisConnect()
        {
            try
            {
                if (serialPort.IsOpen == true)//若打开则关闭
                    this.serialPort.Close();
            }
            catch (Exception ex)
            {

                return false;
            }
            return true;
        }



        #endregion


        #region 接收数据、解析数据


        //数据的接收
        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            if (serialPort.IsOpen == false)
                return;
            //1.获取缓冲区的数据的长度
            int length = this.serialPort.BytesToRead;


            //2.创建临时缓冲区接收数据
            if (length >= 44 * 2)//一次有效报文长度为44B,*2提高有效报文覆盖率，两倍即可在任意情况下覆盖，
                                 //即从缓冲区取出的报文数据一定能找到关键帧(前提是一直在发送关键帧，关键帧相连)。
            {
                //Console.WriteLine(length);

                //创建缓冲区准备接收
                byte[] buffer = new byte[length];

                //读取至缓冲区
                this.serialPort.Read(buffer, 0, length);

                //3.将字节数组信息给到主线程（委托）--解析数据
                myGetMsg(buffer);
            }
        }


        #endregion


    }
}
